<template>
  <el-dialog id="UncommonWordDialog" :visible.sync="visible" title="选择生僻字" width="600px"
             @closed='closedDialog'
             @open="openDialog"
             append-to-body>

    <el-input style="margin: 10px 0px;" placeholder="请输入读音或形似字搜索" v-model.trim="searchInput"
              class="input-with-select">
    </el-input>

    <el-table highlight-current-row border @row-click="clickRow"
              :data="filteredGridData.slice((currentPage-1)*pageSize,currentPage*pageSize)">
      <el-table-column property="spellCode" label="读音" width="150"></el-table-column>
      <el-table-column property="content" label="生僻字" width="150">
        <template slot-scope="scope">
          <img :src="scope.row.content" style="width: 25px"/>
        </template>
      </el-table-column>
      <el-table-column property="similarWord" label="形似字"></el-table-column>
      <el-table-column property="remark" label="备注"></el-table-column>
    </el-table>
    <el-pagination style="margin-top: 10px; text-align: center;"
                   background small
                   :current-page.sync="currentPage"
                   :page-size='pageSize'
                   :total="filteredGridData.length"
                   layout="total, prev, pager, next, jumper">
    </el-pagination>
  </el-dialog>
</template>

<script>
  export default {
    computed : {
      filteredGridData() {
        // 计算属性必须有返回值
        var filteredGridData = []
        if (this.searchInput) {
          this.gridData.forEach((item)=>{
            if(item.spellCode.includes(this.searchInput) || item.similarWord.includes(this.searchInput)){
              filteredGridData.push(item)
            }
          })
          return filteredGridData;
        } else {
          return this.gridData;
        }
      },
    },
    data() {
      return {
        searchInput: '',
        visible: false,
        pageSize: 5,
        currentPage: 1,
        gridData: [],
      }
    },
    methods: {
      openDialog() {
        this.axios.get(CONST.SERVICE_REST_PACKAGE + 'UncommonWordCtrl/selectAll')
          .then((response) => {
            this.gridData = response.data;
          })
          .catch((error) => {
            console.error(error);
            this.gridData = [];
            this.$message.error("未能请求到生僻字数据");
          });
      },
      clickRow(row) {
        let imgStr = `<img data-similar-word=${row.similarWord} data-bz-id=${row.id} title=${row.spellCode} class="rw_img bz" src="${row.path}"/>`
        if (!this.$parent.content){
          this.$parent.editor.html('<p>' + imgStr + '</p>')
        }
        else {
          this.$parent.editor.insertHtml(imgStr)
        }
        this.closedDialog()
      },
      closedDialog() {
        this.searchInput = ''
        this.visible = false
      }
    }
  }
</script>

<style>
  #UncommonWordDialog .el-dialog__body {
    padding-top: 0px;
  }
</style>
